﻿using Application.App.Command;
using Application.Common.Interface;
using Domain;
using MediatR;
using Microsoft.Extensions.Hosting;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Sockets;

namespace WebApi.Works
{
    /// <summary>
    /// 维护设备的状态
    /// </summary>
    public class DeviceStateWork : IHostedService
    {
        private readonly IMediator _mediator;
        private readonly ICustomTcpClient _customTcpClient;
        public DeviceStateWork(IMediator mediator, ICustomTcpClient customTcpClient)
        {
            _mediator = mediator;
            _customTcpClient = customTcpClient;
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _ = Task.Factory.StartNew(async () =>
            {
                while (true)
                {
                    await Task.Delay(3000);
                    foreach (var key in Consts.devices.Keys)
                    {
                        var dev = Consts.devices[key];
                        //出酒中不能再调用，积攒太多容易死
                        if (dev.OOWState != 0)
                            continue;

                        if (DateTime.UtcNow.AddHours(8) - dev.LastUpCmdTime <= TimeSpan.FromSeconds(40))
                            continue;
                        //当40秒内无上行命令会触发一次上行(40s经测试可以保证设备一直在线，暂时去掉依靠自动上传心跳检查在线状态)
                        //await _mediator.Send(new SendCommand { DeviceId = key, CmdType = Domain.Enums.DataType.查询设备命令下 });
                    }
                }
            });
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
